import { type RefObject, useEffect, useRef } from 'react';
import type { IroColorPicker } from '@jaames/iro/dist/ColorPicker';
import iro from '@jaames/iro';

export default function IroItem({
  inputColor,
  selectColorModeRef,
  changeColorCallback,
}: {
  inputColor: string | undefined;
  selectColorModeRef: RefObject<HTMLSelectElement>;
  changeColorCallback: (color: string) => void;
}) {
  const colorIroRef = useRef<IroColorPicker>();
  const colorPickerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function changeColor(color: any) {
      let colorString = '';
      if (selectColorModeRef.current) {
        const value = selectColorModeRef.current.value;
        if (value === 'HEX') {
          colorString = color.hexString;
        } else if (value === 'RGB') {
          colorString = color.rgbString;
        } else if (value === 'RGBA') {
          colorString = color.rgbaString;
        } else if (value === 'HSL') {
          colorString = color.hslString;
        } else if (value === 'HSLA') {
          colorString = color.hslaString;
        }
      }

      changeColorCallback(colorString);
    }

    const current = colorPickerRef.current;
    const colorIro = colorIroRef.current;
    if (current && !colorIro) {
      colorIroRef.current = iro.ColorPicker(current, {
        color: '#ffffff',
        layoutDirection: 'horizontal',
        layout: [
          {
            component: iro.ui.Wheel,
            options: {},
          },
          {
            component: iro.ui.Slider,
            options: {
              sliderType: 'hue',
            },
          },
          {
            component: iro.ui.Slider,
            options: {
              sliderType: 'saturation',
            },
          },
          {
            component: iro.ui.Slider,
            options: {
              sliderType: 'value',
            },
          },
          {
            component: iro.ui.Slider,
            options: {
              sliderType: 'alpha',
            },
          },
          {
            component: iro.ui.Slider,
            options: {
              sliderType: 'kelvin',
            },
          },
        ],
      });

      colorIroRef.current.on('color:change', changeColor);
    }

    return () => {
      if (colorIro) {
        colorIro.off('color:change', changeColor);
      }
    };
  }, []);
  useEffect(() => {
    const current = colorIroRef.current;
    if (inputColor && current) {
      current.color.set(inputColor);
    }
  }, [inputColor]);

  return <div ref={colorPickerRef}></div>;
}
